package com.mvd.app.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.mvd.app.R;
import com.mvd.app.ac_wenzhou.ReCheckHuanBaoTakePhotoActivity;
import com.mvd.app.adapter.RecheckCarsListAdapter;
import com.mvd.app.application.BaseApplication;
import com.mvd.app.commons.CommonUtils;
import com.mvd.app.commons.DateUtil;
import com.mvd.app.commons.JsonUtil;
import com.mvd.app.commons.PDALogUtils;
import com.mvd.app.commons.SharedPreferencesUtils;
import com.mvd.app.commons.Utils;
import com.mvd.app.commons.UtilsLog;
import com.mvd.app.model.RecheckCarsModel;
import com.mvd.app.model.RecheckJsonModel;
import com.mvd.app.widget.EditTextViewWorksSizeCheckUtil;
import com.mvd.app.widget.IEditTextChangeListener;

import java.text.Collator;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.stream.Collector;
import java.util.stream.Collectors;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static android.R.id.list;

/**
 * 复检拍照,查询  车辆列表
 */
public class RecheckPhotoListActivity extends BaseActivity implements AdapterView.OnItemClickListener {

    @BindView(R.id.ac_rechreck_list)
    ListView acRechreckList;
    public RecheckPhotoListActivity instances = null;
    @BindView(R.id.ac_daijian_et_search22)
    EditText acDaijianEtSearch22;
    @BindView(R.id.ac_recheck_start_time)
    TextView acRecheckStartTime;
    @BindView(R.id.ac_recheck_end_time)
    TextView acRecheckEndTime;
    @BindView(R.id.ac_daijian_btn_search22)
    Button acDaijianBtnSearch22;
    @BindView(R.id.ac_daijian_bt_type22)
    Button acDaijianBtType22;

    private String carNO = null;
    private String StartTime = null;
    private String EndTime = null;
    private int CHECK_MODE = 0;//检测模式 0:外检  1：路试 2：底盘动态
    private String CURRENT_CHECK_MODE = "";//当前检测模式

    final Calendar ca = Calendar.getInstance();
    int mYear, mMonth, mDay;
    final int DATE_DIALOG = 1;
    final int DATE_DIALOG2 = 2;

    RecheckJsonModel recheckJsonModel;//复检查询上传json用到

    List<RecheckCarsModel> recheckCarsModelList = new ArrayList<>();//复检查询到的车辆列表
    List<RecheckCarsModel> recheckCarsModelList2 = new ArrayList<RecheckCarsModel>();

    List<RecheckCarsModel> filtering_recheckCarsModelList = new ArrayList<>();//复检查询到的车辆列表-过滤后的
    RecheckCarsListAdapter recheckCarsListAdapter;
    private String Login_name = "", login_IDNumber, login_username;//当前登录的检测员的名字
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);

        setContentView(R.layout.activity_recheck_photo);
        ButterKnife.bind(this);
        acRechreckList.setOnItemClickListener(this);
        setTopTitle(R.string.activity_daijian_car_list);
        instances = this;
        setBackBtn();
        CHECK_MODE = 0;
        switch (0) {
            //检测模式 0:外检  F1 1：路试 R1 2：底盘动态 DC
            case 0:
                CURRENT_CHECK_MODE = "F1";
                break;
            case 1:
                CURRENT_CHECK_MODE = "R1";
                break;
            case 2:
                CURRENT_CHECK_MODE = "DC";
                break;
        }

        Login_name = getIntent().getExtras().getString("login_UserID", "");
        login_IDNumber = getIntent().getExtras().getString("login_IDNumber", "");
        login_username = getIntent().getExtras().getString("login_username", "");
        mYear = ca.get(Calendar.YEAR);
        mMonth = ca.get(Calendar.MONTH);
        mDay = ca.get(Calendar.DAY_OF_MONTH);

        acRecheckStartTime.setText(DateUtil.getTodayDate2());
        acRecheckEndTime.setText(DateUtil.getTodayDate2());
        recheckJsonModel = new RecheckJsonModel();
        acRechreckList.setVisibility(View.GONE);

//        acDaijianEtSearch22.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);

//        acDaijianEtSearch22.requestFocus();
//        InputMethodManager inputMethodManager = (InputMethodManager) instances.getSystemService(Context.INPUT_METHOD_SERVICE);
////        inputMethodManager.showSoftInput(acDaijianEtSearch22, InputMethodManager.SHOW_IMPLICIT);
//        inputMethodManager.toggleSoftInput(0, InputMethodManager.SHOW_FORCED);


//        //1.创建工具类对象 把要改变颜色的tv先传过去
//        EditTextViewWorksSizeCheckUtil.textChangeListener textChangeListener = new
//                EditTextViewWorksSizeCheckUtil.textChangeListener(acDaijianBtnSearch22);
//
//        //2.把所有要监听的edittext都添加进去
//        textChangeListener.addAllEditText(acDaijianEtSearch22);
//
//        //3.接口回调 在这里拿到boolean变量 根据isHasContent的值决定 tv 应该设置什么颜色
//        EditTextViewWorksSizeCheckUtil.setChangeListener(new IEditTextChangeListener() {
//            @Override
//            public void textChange(boolean isHasContent) {
//                if (isHasContent) {
//                    acDaijianBtnSearch22.setTextColor(Color.WHITE);
//                    acDaijianBtnSearch22.setEnabled(true);
//                } else {
//                    acDaijianBtnSearch22.setTextColor(Color.GRAY);
//                    acDaijianBtnSearch22.setEnabled(false);
//                }
//            }
//        });


//        Timer timer = new Timer();
//        timer.schedule(new TimerTask() {
//
//            public void run() {
//                InputMethodManager inputManager = (InputMethodManager) acDaijianEtSearch22.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//                inputManager.showSoftInput(acDaijianEtSearch22, 0);
//            }
//
//        }, 800);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (CommonUtils.isOnline(this)) {

        } else {
            Toast.makeText(this, getResources().getString(R.string.network_error), Toast.LENGTH_LONG)
                    .show();
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        RecheckCarsModel model = (RecheckCarsModel) parent.getAdapter().getItem(position);
        Intent intent2 = null;
        if (model.getAn_huan_type() == 0) {
            intent2 = new Intent(instances, ReCheckTakePhotoActivity.class);
        } else {
            intent2 = new Intent(instances, ReCheckHuanBaoTakePhotoActivity.class);
        }
        intent2.putExtra("re_model", model);
        intent2.putExtra("login_UserID", Login_name);
        intent2.putExtra("login_username", login_username);
        intent2.putExtra("login_IDNumber", login_IDNumber);
        startActivity(intent2);
    }

    @OnClick({R.id.ac_daijian_btn_search22, R.id.ac_recheck_start_time,
            R.id.ac_recheck_end_time, R.id.ac_daijian_et_search22})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ac_daijian_btn_search22:
                //查询
                carNO = acDaijianEtSearch22.getText().toString().trim();
                StartTime = acRecheckStartTime.getText().toString().trim();
                EndTime = acRecheckEndTime.getText().toString().trim();
                if (!TextUtils.isEmpty(carNO)) {
                    filtering_recheckCarsModelList = new ArrayList<RecheckCarsModel>();
                    recheckJsonModel.setPlateNO(carNO);
                    recheckJsonModel.setEndDate(EndTime);
                    recheckJsonModel.setStartDate(StartTime);
                    recheckJsonModel.setType("0");
                    recheckCarsModelList = new ArrayList<RecheckCarsModel>();
                    getDataSearchCarsByNO(recheckJsonModel, 1);
                    Handler handler = new Handler();
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            recheckJsonModel.setType("1");
                            recheckCarsModelList2 = new ArrayList<RecheckCarsModel>();
                            getDataSearchCarsByNO(recheckJsonModel, 2);
                        }
                    }, 600);//后执行Runnable中的run方法
                } else {
                    Toast.makeText(instances, "车牌号码不能为空", Toast
                            .LENGTH_LONG).show();
                }
                break;
            case R.id.ac_recheck_start_time:
                //开始时间
                showDialog(DATE_DIALOG);
                break;
            case R.id.ac_recheck_end_time:
                //结束时间
                showDialog(DATE_DIALOG2);
                break;
//            case R.id.ac_daijian_et_search22:
//                //输入框，软键盘
//                showSoftInputFromWindow(acDaijianEtSearch22);
////                acDaijianEtSearch22.setFocusable(true);
//                break;
        }
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
            case DATE_DIALOG:
                return new DatePickerDialog(this, mdateListener, mYear, mMonth, mDay);
            case DATE_DIALOG2:
                return new DatePickerDialog(this, mdateListener2, mYear, mMonth, mDay);
        }
        return null;
    }

    /**
     * 设置日期 利用StringBuffer追加
     */

    public void display(TextView tv) {
        tv.setText(new StringBuffer().append(mYear).append("-").append(mMonth + 1).append("-").append(mDay)
                .append(" "));
    }

    private DatePickerDialog.OnDateSetListener mdateListener = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display(acRecheckStartTime);
        }
    };
    private DatePickerDialog.OnDateSetListener mdateListener2 = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            mYear = year;
            mMonth = monthOfYear;
            mDay = dayOfMonth;
            display(acRecheckEndTime);
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
        instances = null;
    }


    //复检查询
    //carNO 车牌号码
    private void getDataSearchCarsByNO(RecheckJsonModel recheckJsonModel, int count) {
        Gson gson = new Gson();
        String json_str = gson.toJson(recheckJsonModel);
        UtilsLog.e("getDataSearchCarsByNO---json_str==" + json_str);
        UtilsLog.e("getDataSearchCarsByNO---url==" + SharedPreferencesUtils.getIP(this) + RECHECK_CARS_LIST);

        String logStr = "\n" + "复检查询-补传照片-查询----json" + "\n" +
                "URL::" + SharedPreferencesUtils.getIP(instances) + RECHECK_CARS_LIST
                + "\n" + "json" + json_str;
        PDALogUtils.createLogFile(0, logStr.getBytes());

        OkGo.<String>post(SharedPreferencesUtils.getIP(this) + RECHECK_CARS_LIST).tag(this)
                .upJson(json_str)
                .execute(new StringCallback() {
                    @Override
                    public void onStart(Request<String, ? extends Request> request) {
                        super.onStart(request);
                        CommonUtils.showLoadingDialog(instances, "加载中...");
                    }

                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
//                        UtilsLog.e("getDataSearchCarsByNO-result==" + result);
                        String newResult = result.substring(1, result.length() - 1).replaceAll("\\\\", "");
                        UtilsLog.e("getDataSearchCarsByNO-newResult==" + newResult);

                        String logStr = "\n" + "复检查询-补传照片-查询----onSuccess" + "\n" +
                                "result:" + "\n" + result + "\n";
                        PDALogUtils.createLogFile(0, logStr.getBytes());

                        if (!TextUtils.isEmpty(newResult) && !"[[]]".equals(newResult) && !"[{}]".equals
                                (newResult) && !"[]".equals(newResult)) {
                            RecheckCarsModel model = null;
                            if (count == 1) {
                                //安检
                                recheckCarsModelList = JsonUtil.stringToArray(newResult, RecheckCarsModel[]
                                        .class);
                                if (recheckCarsModelList != null && recheckCarsModelList.size() > 0) {
                                    for (int i = 0; i < recheckCarsModelList.size(); i++) {
                                        model = new RecheckCarsModel();
                                        model = recheckCarsModelList.get(i);
                                        model.setAn_huan_type(0);
                                        filtering_recheckCarsModelList.add(model);
                                    }
                                } else {
                                    acRechreckList.setVisibility(View.GONE);
                                    Toast.makeText(instances, "没有查询到相关车辆", Toast
                                            .LENGTH_LONG).show();
                                }
                            } else {
                                //环保
                                recheckCarsModelList2 = JsonUtil.stringToArray(newResult, RecheckCarsModel[]
                                        .class);
                                if (recheckCarsModelList2 != null && recheckCarsModelList2.size() > 0) {
                                    for (int i = 0; i < recheckCarsModelList2.size(); i++) {
                                        model = new RecheckCarsModel();
                                        model = recheckCarsModelList2.get(i);
                                        model.setAn_huan_type(1);
                                        filtering_recheckCarsModelList.add(model);
//                                        filtering_recheckCarsModelList.add(recheckCarsModelList.get(i));
                                    }
                                } else {
                                    acRechreckList.setVisibility(View.GONE);
                                    Toast.makeText(instances, "没有查询到相关车辆", Toast
                                            .LENGTH_LONG).show();
                                }
                            }

                            if (filtering_recheckCarsModelList != null && filtering_recheckCarsModelList.size() > 0) {
                                for (int i = 0; i < filtering_recheckCarsModelList.size(); i++) {
                                    UtilsLog.e("filtering_recheckCarsModelList-=====" + filtering_recheckCarsModelList.get(i).toString());
                                }
                                recheckCarsListAdapter = new RecheckCarsListAdapter(RecheckPhotoListActivity.this,
                                        filtering_recheckCarsModelList);
                                acRechreckList.setAdapter(recheckCarsListAdapter);
                                acRechreckList.setVisibility(View.VISIBLE);
                                String logStr2 = "\n" + "复检查询-补传照片-查询----onSuccess" + "\n" +
                                        "filtering_recheckCarsModelList:" + "\n" + filtering_recheckCarsModelList.toString() + "\n";
                                PDALogUtils.createLogFile(0, logStr2.getBytes());
                            } else {
                                Toast.makeText(instances, "没有查询到相关车辆", Toast
                                        .LENGTH_LONG).show();
                            }

                        } else {
                            if (filtering_recheckCarsModelList != null && filtering_recheckCarsModelList.size() > 0) {
                                for (int i = 0; i < filtering_recheckCarsModelList.size(); i++) {
                                    UtilsLog.e("filtering_recheckCarsModelList-=====" + filtering_recheckCarsModelList.get(i).toString());
                                }
                                recheckCarsListAdapter = new RecheckCarsListAdapter(RecheckPhotoListActivity.this,
                                        filtering_recheckCarsModelList);
                                acRechreckList.setAdapter(recheckCarsListAdapter);
                                acRechreckList.setVisibility(View.VISIBLE);
                                String logStr2 = "\n" + "复检查询-补传照片-查询----onSuccess" + "\n" +
                                        "filtering_recheckCarsModelList:" + "\n" + filtering_recheckCarsModelList.toString() + "\n";
                                PDALogUtils.createLogFile(0, logStr2.getBytes());
                            } else {
                                Toast.makeText(instances, "没有查询到相关车辆", Toast
                                        .LENGTH_LONG).show();
                                acRechreckList.setVisibility(View.GONE);
                                UtilsLog.e("getDataSearchCarsByNO-result==" + "没有数据");
                            }
                        }
                        CommonUtils.hideLoadingDialog(instances);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        String logStr = "\n" + "补传照片--查询----onError" + "\n" +
                                "result:" + "\n" + response.body() + "\n";
                        PDALogUtils.createLogFile(0, logStr.getBytes());
                        UtilsLog.e("getDataSearchCarsByNO-onError==" + response.body());
                        CommonUtils.hideLoadingDialog(instances);
                    }
                });
    }

}
